import React, { Component } from 'react'
//引入父组件AdminLayout
import AdminLayout from "@components/AdminLayout"
//引入二级路由
import {adminRoute} from "@routes"
//引入配置路由的插件
import {Switch,Route,Redirect} from "react-router-dom"

export default class Admin extends Component {
  render() {
    return (
      <AdminLayout>
          <Switch>
            {/* 循环渲染，循环渲染adminRoute */}
            {
              adminRoute.map((route)=>{
                return (
                  <Route
                  key={route.path}
                  path={route.path}
                  //让其拥有路由组件的api
                  render={(routerProps)=>{
                    //获取token
                    const token =localStorage.getItem('accessToken')
                    return(
                      token?
                     (function(){
                      //  拿到当前路由可访问的角色列表
                       let roles=route.meta.roles
                       //拿到当前用户的角色
                       let userInfo=JSON.parse(localStorage.getItem("userInfo"))
                       //利用遍历获取布尔值做判断
                       let hasAuthority=roles.some(role=>role===userInfo.role) 
                       if(hasAuthority){
                         return(
                           //让其拥有路由组件的api
                           <route.component {...routerProps}/>
                         )
                       }else{
                         return <Redirect to="/admin/noAuthority"/>
                       }
                     }()):
                      <Redirect to={
                        {pathname:"/login",
                        state:{form:route.path}
                      }}/>
                    )
                  }}
                  /> 
                )
              })
            }
            {/* 重定向 */}
            <Redirect to="/admin/dashBoard" from="/admin" exact/>
            <Redirect to="/admin/404"/>
          </Switch>
      </AdminLayout>
    )
  }
}
